package com.study.talk.ui.app.friend

import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.study.common.DateUtil
import com.study.common.ToastUtil
import com.study.common.annotation.Desc
import com.study.talk.ui.app.base.BaseViewModel
import com.study.talk.data.model.UserInfo
import com.study.talk.netty.NettyClient
import com.study.talk.netty.message.request.AddUserRequest
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class UserDetailsViewModel @Inject constructor(
    application: Application
) : BaseViewModel(application) {

    private val _user = MutableLiveData<UserInfo>()
    val user: LiveData<UserInfo> get() = _user

    private val _isFriend = MutableLiveData(false)
    val isFriend: LiveData<Boolean> get() = _isFriend

    fun loadUser(userId: Int) {
        viewModelScope.launch {
            val result = userRepository.requestUserInfo(userId)
            if (result == null) {
                ToastUtil.showToast(app, "获取用户信息失败")
            } else {
                result.let {
                    _user.postValue(it)
                }
            }
        }
    }

    @Desc("查询是否为自己好友")
    fun queryIsMyFriend(userId: Int) {
        viewModelScope.launch {
            val result = userRepository.friend(userId)
            if (result == null) {
                ToastUtil.showToast(app, "好友关系查询失败")
            } else {
                _isFriend.postValue(result)
            }
        }
    }

    fun changeStatus(status: Boolean) {
        _isFriend.postValue(status)
    }

    fun deleteFriend(userId: Int) {
        viewModelScope.launch {
            val result = userRepository.deleteFriend(userId)
            if (result == null) {
                ToastUtil.showToast(app, "好友关系查询失败")
            } else {
                _isFriend.postValue(result)
            }
        }
    }

    fun addFriendRequest(id : Int){
        NettyClient.sendMessage(AddUserRequest(app.localUserId,id,DateUtil.currentTime()))
    }
}